<template>
    <div class="report-list">
        <div class="page-header">
            <h1>报告列表</h1>
            <a-space>
                <a-button @click="fetchDocuments">刷新列表</a-button>
                <a-button type="primary" @click="handleUpload">上传报告</a-button>
            </a-space>
        </div>

        <a-table :columns="columns" :data-source="documents" :loading="loading" :pagination="{ pageSize: 10 }"
            row-key="id">
            <template #bodyCell="{ column, record }">
                <!-- 封面图片 -->
                <template v-if="column.key === 'cover'">
                    <img v-if="record.cover_image_url" :src="record.cover_image_url" alt="封面" class="cover-image" />
                    <span v-else>无封面</span>
                </template>

                <!-- 报告名称 -->
                <template v-if="column.key === 'file_name'">
                    <a href="#" @click.prevent="viewDocument(record.id)">{{ record.file_name }}</a>
                </template>

                <!-- 状态 -->
                <template v-if="column.key === 'status'">
                    <!-- {{ record.parsing_status}} -->
                    <a-tag v-if="record.parsing_status === 'pending'" color="orange">待解析</a-tag>
                    <a-tag v-else-if="record.parsing_status === 'processing'" color="blue">解析中</a-tag>
                    <a-tag v-else-if="record.parsing_status === 'completed'" color="green">解析成功</a-tag>
                    <a-tag v-else color="red">解析失败</a-tag>
                </template>

                <!-- 总结状态 -->
                <template v-if="column.key === 'summary_status'">
                    <a-tag v-if="record.summary_status === 'pending'" color="orange">待总结</a-tag>
                    <a-tag v-else-if="record.summary_status === 'processing'" color="blue">总结中</a-tag>
                    <a-tag v-else-if="record.summary_status === 'completed'" color="green">已完成</a-tag>
                    <a-tag v-else-if="record.summary_status === 'failed'" color="red">总结失败</a-tag>
                    <a-tag v-else color="default">未总结</a-tag>
                </template>

                <!-- 创建时间 -->
                <template v-if="column.key === 'created_at'">
                    {{ formatDateTime(record.created_at) }}
                </template>

                <!-- 操作 -->
                <template v-if="column.key === 'action'">
                    <a-space>
                        <a-button type="link" @click="viewDocument(record.id)">查看</a-button>
                        <a-button type="link">编辑</a-button>
                        <a-button v-if="record.parsing_status != 'completed'" type="link"
                            :loading="record.parsing_status == 'processing'"
                            @click="handlePressParseDocument(record)">解析</a-button>
                        <a-button v-if="record.parsing_status == 'completed' && record.summary_status != 'completed'"
                            type="link" :loading="record.summary_status == 'processing'"
                            @click="handleSummarizeDocument(record)">总结</a-button>
                        <a-button type="link" danger>删除</a-button>
                    </a-space>
                </template>
            </template>
        </a-table>

        <!-- 文件上传输入 (隐藏) -->
        <input type="file" ref="fileInput" style="display: none" @change="onFileSelected" accept=".pdf,.doc,.docx" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getDetectionReports, parseDetectionReport, uploadDetectReport, summarizeDetectionReport, parseOriginDocument } from '@/api/documents'
import type { DetectionReport } from '@/api/documents'
import axios from 'axios'
import { useRouter } from 'vue-router'

// 扩展Document类型
// interface ParseDocument extends DetectionReport {
//     parsing: boolean;
//     summarizing: boolean;
// }

const documents = ref<DetectionReport[]>([])
const loading = ref<boolean>(false)
const fileInput = ref<HTMLInputElement | null>(null)
const uploadLoading = ref<boolean>(false)
const router = useRouter()

// 格式化日期时间函数
const formatDateTime = (dateTimeStr: string): string => {
    if (!dateTimeStr) return '';
    try {
        const date = new Date(dateTimeStr);
        return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateTimeStr;
    }
}

// 补零函数
const padZero = (num: number): string => {
    return num < 10 ? `0${num}` : `${num}`;
}

const columns = [
    {
        title: '封面',
        key: 'cover',
        width: 100,
    },
    {
        title: '报告名称',
        dataIndex: 'file_name',
        key: 'file_name',
    },
    {
        title: '页数',
        dataIndex: 'page_count',
        key: 'page_count',
        width: 100,
    },
    {
        title: '解析状态',
        key: 'status',
        width: 120,
    },
    {
        title: '总结状态',
        key: 'summary_status',
        width: 120,
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: 180,
    },
    {
        title: '操作',
        key: 'action',
        width: 200,
    },
]

const fetchDocuments = async () => {
    loading.value = true
    try {
        const response = await getDetectionReports()
        documents.value = response.map((doc: DetectionReport) => ({
            ...doc,
            parsing: false, // 添加解析中状态标记
            summarizing: false // 添加总结中状态标记
        }))
    } catch (error) {
        console.error('获取文档列表失败:', error)
        message.error('获取文档列表失败')
    } finally {
        loading.value = false
    }
}

const viewDocument = (id: number) => {
    console.log('查看文档:', id)
    // 跳转到文档详情页
    router.push(`/dashboard/report-detail/${id}`)
}

// 触发文件选择
const handleUpload = () => {
    fileInput.value?.click()
}

// 选择文件后上传
const onFileSelected = async (event: Event) => {
    const input = event.target as HTMLInputElement
    const files = input.files

    if (!files || files.length === 0) {
        return
    }

    const file = files[0]
    uploadLoading.value = true

    try {
        const response = await uploadDetectReport(file)

        if (response.success) {
            message.success('报告上传成功')
            // 刷新文档列表
            fetchDocuments()
        } else {
            message.error(response.message || '上传失败')
        }
    } catch (error: any) {
        console.error('上传报告失败:', error)
        message.error(error.response?.data?.error || '上传报告失败')
    } finally {
        uploadLoading.value = false
        // 清空文件输入，以便重新选择同一文件
        if (fileInput.value) {
            fileInput.value.value = ''
        }
    }
}

const handlePressParseDocument = async (report: DetectionReport) => {
    // 设置文档为解析中状态
    report.parsing = true

    try {
        const response = await parseDetectionReport(report.id)

        if (response.success) {
            message.success(response.message || '文档解析已启动')
            // 刷新文档列表
            fetchDocuments()
        } else {
            message.error(response.message || '解析启动失败')
        }
    } catch (error: any) {
        console.error('解析文档失败:', error)
        message.error(error.response?.data?.error || '解析文档失败')
    } finally {
        report.parsing = false
    }
}

const handleSummarizeDocument = async (report: DetectionReport) => {
    // 设置文档为总结中状态
    report.summarizing = true

    try {
        const response = await summarizeDetectionReport(report.id)

        if (response.success) {
            message.success(response.message || '文档总结已启动')
            // 刷新文档列表
            fetchDocuments()
        } else {
            message.error(response.message || '总结启动失败')
        }
    } catch (error: any) {
        console.error('总结文档失败:', error)
        message.error(error.response?.data?.error || '总结文档失败')
    } finally {
        report.summarizing = false
    }
}

onMounted(() => {
    fetchDocuments()
})
</script>

<style scoped>
.report-list {
    padding: 24px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
}

.cover-image {
    width: 60px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
}
</style>